package com.hgdp.medicalexamination.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgdp.medicalexamination.Dto.MaleAndFmaleDto;
import com.hgdp.medicalexamination.entity.Male;
import com.hgdp.medicalexamination.mapper.FmaleMapper;
import com.hgdp.medicalexamination.mapper.MaleMapper;
import com.hgdp.medicalexamination.vo.FmaleAndMaleVo;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hgdp.medicalexamination.service.MaleService;
import lombok.AllArgsConstructor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @param /婚前医学检查表(男性)信息
 * @author hgdp
 * @date 2020-07-29 15:19:30
 */

@Service
@AllArgsConstructor
public class MaleServiceImpl extends ServiceImpl<MaleMapper, Male> implements MaleService {
	private MaleMapper maleMapper;
	private FmaleMapper fmaleMapper;
	
	@Override
	public IPage<Male> queryPage(Page page, Male male) {
		IPage<Male> pages =baseMapper.selectPage(page, Wrappers.query(male));
		page.setTotal(baseMapper.selectCount(Wrappers.query(male)));
		return pages;
	}

	@Override
	public R insertMale(MaleAndFmaleDto maleAndFmaleDto) {
		if (maleAndFmaleDto.getMale()==null || maleAndFmaleDto.getFmale()==null){
			return R.ok(false);
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String currentDate = dateFormat.format( new Date() ).replace("-","");
		Random random = new Random();
		int Num;
		do {
			Num = random.nextInt(900) + 100;
		}while (existenceId(Num,currentDate));
		maleAndFmaleDto.getMale().setId(currentDate+Num+1);
		maleAndFmaleDto.getMale().setFmaleId(currentDate+Num+2);
		maleAndFmaleDto.getFmale().setMaleId(currentDate+Num+1);
		maleAndFmaleDto.getFmale().setId(currentDate+Num+2);
		maleMapper.insert(maleAndFmaleDto.getMale());
		fmaleMapper.insert(maleAndFmaleDto.getFmale());
		return R.ok(true);
	}

	@Override
	public List<FmaleAndMaleVo> selectByTime(Page page, String startTime, String endTime) {
		List<FmaleAndMaleVo> fmaleAndMaleVos = maleMapper.selectByTime(page, startTime, endTime);
		for (FmaleAndMaleVo fmaleAndMaleVo : fmaleAndMaleVos) {
			if (fmaleAndMaleVo.getId().substring(fmaleAndMaleVo.getId().length()-1).equals("1")){
				fmaleAndMaleVo.setSex("男");
			}else {
				fmaleAndMaleVo.setSex("女");
			}
		}
		return fmaleAndMaleVos;
	}

	//判断id是否重复工具
	public Boolean existenceId(int id,String date){
		List<String> strings = maleMapper.selectAllId(date);
		if (strings.size()>0){
			for (String string : strings) {
				if (String.valueOf(id).equals(string.substring(8,11))){
					return true;
				}
			}
		}

		return false;
	}
}